

local FrameLoader = require("Utils.FrameLoader")
local PrefabFactory = require("Utils.PrefabFactory")
local Consts = require("Data.Consts")
local UINodes = require("Data.UINodes")

--- main.lua
-- require "ClassUtils"
local MathUtils = require("Utils.MathUtils")


G = {}
G.frameLoader = FrameLoader.new(6, 1) -- 分帧加载器
G.prefabFactory = PrefabFactory.new()
G.tickables = {G.frameLoader}

local money = 0
local UInodes = require("Data.UINodes")
local GenerateController = require("GenerateController")
local region = LuaAPI.query_unit("通用触发区域3")

local startPoint = LuaAPI.query_unit("起点1")
local endPoint = LuaAPI.query_unit("通用触发区域4")

local block = LuaAPI.query_unit("旋转中心")
local atkValue = 1

local role = GameAPI.get_all_valid_roles()[1]
local player = role.get_ctrl_unit()


LuaAPI.global_register_trigger_event({EVENT.ANY_LIFEENTITY_TRIGGER_SPACE, Enums.TriggerSpaceEventType.ENTER,
                                      region.get_id()}, function(name, actor, data)

    local unit = data.event_unit
        --    GameAPI.apply_damage(unit, 1000.0, region, 1)                            
    -- if unit.has_tag("障碍物") then
    --     local oriHp = unit.get_kv_by_type(Enums.ValueType.Int, "hp")
    --     oriHp = oriHp - atkValue
    --     -- print("HP:" .. oriHp)
    --     if (oriHp <= 0) then


end)



LuaAPI.global_register_trigger_event({EVENT.ANY_OBSTACLE_TRIGGER_SPACE, Enums.TriggerSpaceEventType.ENTER,
                                      region.get_id()}, function(name, actor, data)

    local unit = data.event_unit
    
    if unit.has_tag("障碍物") then
        local oriHp = unit.get_kv_by_type(Enums.ValueType.Int, "hp")
        oriHp = oriHp - atkValue
        -- print("HP:" .. oriHp)
        if (oriHp <= 0) then
            -- GameAPI.destroy_unit(unit)
            G.prefabFactory:destroyPrefab(unit)
            role.change_attr_bonus_fixed(Consts.CoinType.Gold,50.0)
            -- role.set_label_text(UInodes["金币文本"],tostring(role.get_attr_bonus_fixed(Consts.CoinType.Gold)))
        end
        unit.set_kv_by_type(Enums.ValueType.Int, "hp", oriHp)
        unit.apply_force(math.Vector3(200, 200, 0))
    else
            -- print("不是障碍物")
            -- print(unit.get_unit_type())
    end
    


end)

local generateController = GenerateController.new() -- 物体管理器

generateController:generateObjects(startPoint, 1073786899, 20, 20, nil)



function updateBlockPos()
    block.set_position(player.get_position())
end
function G.addTickable(obj)
    assert(obj.update)
    table.insert(G.tickables, obj)
end

-- 移除可更新对象的函数
function G.removeTickable(obj)
    for i, v in ipairs(G.tickables) do
        if v == obj then
            table.remove(G.tickables, i)
            break
        end
    end
end
-- 帧更新处理函数
local function onPreTick(_)
  
    for _, v in ipairs(G.tickables) do
        v:update()
    end
    updateBlockPos()
end



-- 设置帧更新处理函数
LuaAPI.set_tick_handler(onPreTick)
